import requests
from datetime import datetime
import json
class Ticktock:
    def __init__(self, session_id):
        self.user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36'
        self.session_id = session_id    


    def get_shop_list(self):
        url = 'https://api16-normal-sg.tiktokglobalshop.com/api/v1/shop_im/multi_shop/user/get_info_list'

        # 请求头
        headers = {
            "accept": "*/*",
            "accept-language": "zh,en-US;q=0.9,en;q=0.8,ja;q=0.7,zh-CN;q=0.6,zh-TW;q=0.5",
            "origin": "https://seller.tiktokglobalshop.com",
            "priority": "u=1, i",
            "referer": "https://seller.tiktokglobalshop.com/",
            "user-agent": self.user_agent,
            "x-tt-oec-region": "VN"
        }

        # Cookie
        cookies = {
            "sessionid": self.session_id,
        }

        # 发送 GET 请求
        response = requests.get(url, headers=headers, cookies=cookies).json()
        if response.get('code') != 0:
            raise Exception(f"获取门店列表失败: {response.get('message')}")
        
        shop_infos = response.get('data', {}).get('shop_infos', {})
        result = []
        for shop_info in shop_infos:
            result.append({
                'outer_shop_id': shop_info['outer_shop_id'],
                'im_shop_id': shop_info['im_shop_id'],
                'shop_region': shop_info['shop_region'],
                'shop_name': shop_info['shop_name'],
            })
        return result

    def get_tt_product_info(self, seller_id, product_id):
        # 请求 URL
        url = 'https://api16-normal-useast1a.tiktokglobalshop.com/api/v1/product/global/product/get'

        # 请求参数
        params = {
            "locale": "zh-CN",
            "language": "zh-CN",
            "oec_seller_id": seller_id,
            "aid": "6556",
            "app_name": "i18n_ecom_shop",
            "fp": "verify_mb08hmy7_cLP8UXlA_rX6l_4e9P_APMd_9t8zXbS4wSTF",
            "device_platform": "web",
            "cookie_enabled": "true",
            "screen_width": "1512",
            "screen_height": "982",
            "browser_language": "zh",
            "browser_platform": "MacIntel",
            "browser_name": "Mozilla",
            "browser_version": "5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
            "browser_online": "true",
            "timezone_name": "Asia/Kuala_Lumpur",
            "product_id": product_id
        }

        # 请求头
        headers = {
            'accept': '*/*',
            'accept-language': 'zh,en-US;q=0.9,en;q=0.8,ja;q=0.7,zh-CN;q=0.6,zh-TW;q=0.5',
            'cache-control': 'no-cache',
            'origin': 'https://seller.tiktokglobalshop.com',
            'pragma': 'no-cache',
            'priority': 'u=1, i',
            'referer': 'https://seller.tiktokglobalshop.com/',
            'sec-ch-ua': '"Chromium";v="136", "Google Chrome";v="136", "Not.A/Brand";v="99"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"macOS"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-site',
            'user-agent': self.user_agent,
        }

        # Cookie
        cookies = {
            "sessionid": self.session_id,
            "sessionid_ss": self.session_id,
        }

        # 发送 GET 请求
        response = requests.get(url, params=params, headers=headers, cookies=cookies)
        response_data = response.json()
        if response_data.get('code') != 0:
            raise Exception(response_data.get('message'))
        
        product = response_data.get('data', {})
        if not product:
            raise Exception('未查询到产品信息')
        
        return product



    def search_tt_products(self, seller_id, page, limit):
        url = 'https://api16-normal-sg.tiktokglobalshop.com/api/v2/promotion/search_products'

        params = {
            'oec_seller_id': seller_id
        }

        headers = {
            'accept': '*/*',
            'accept-language': 'zh,en-US;q=0.9,en;q=0.8,ja;q=0.7,zh-CN;q=0.6,zh-TW;q=0.5',
            'content-type': 'application/json',
            'origin': 'https://seller.tiktokglobalshop.com',
            'priority': 'u=1, i',
            'referer': 'https://seller.tiktokglobalshop.com/',
            'user-agent': self.user_agent,
        }

        cookies = {
            'sessionid': self.session_id,
        }

        start_time = int(datetime.now().timestamp()) + 3600 * 3
        end_time = start_time + 3600 * 24 * 180
        # start_time = 1746462300
        # end_time = 1762014300
        data = {
            "page_index": page - 1,
            "page_size": limit,
            "promotion_type": 4,
            "pagination_type": 0,
            "search_options": {
                "search_with_exist_discount": {
                    "search_period": {
                        "start_time": str(start_time),
                        "end_time": str(end_time)
                    }
                },
                "with_abnormal_check": {
                    "seller_promotion_template": 2
                }
            },
            "promotion_type_detail": 11,
            "search_scenario": 1
        }

        response = requests.post(url, params=params, headers=headers, cookies=cookies, json=data)
        response_data = response.json().get('data', {})
        exist_discount_products = response_data.get('exist_discount_product', [])
        products = response_data.get('products', [])
        # print(params)
        # print(json.dumps(data, indent=4))
        # print(len(exist_discount_products), len(products))
        result = {}
        for product in products:
            skus = []
            for sku in product['skus']:
                skus.append({
                    'sku_id': sku['sku_id'],
                    'sku_name': sku['sku_name'],
                    'inventory_quantity': sku['inventory_quantity'],
                    'is_promote_sku': sku['inventory_quantity'] == 10,
                    'sale_price': float(sku['sale_price_range']['highest_price_value']),
                })
            product_id = product['product_id']
            result[product_id] = {
                'product_id': product_id,
                'exist_discount': product_id in exist_discount_products,
                'skus': skus
            }

        return result    


if __name__ == '__main__':
    tt = Ticktock('e13e279257b83beea95e753f7f61f40d')
    # shop_list = tt.get_shop_list()
    # for shop in shop_list:
    #     print(shop['shop_region'])
    # seller_id = shop_list[0]['outer_shop_id']
    # products = tt.search_tt_products(seller_id, 1, 1000)
    # no_discount_count = 0
    # for product_id, product in products.items():
    #     if not product['exist_discount']:
    #         no_discount_count += 1
    # print(no_discount_count)

    product_id = '1731501290730850250'
    seller_id = '7496123968648743882'
    product_info = tt.get_tt_product_info(seller_id, product_id)
    print(product_info.get('package_weight'))